package de.tum.in.eist.poll.server;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Generates memorable English passwords.
 * 
 * @author The EIST-POLL-21 team.
 * 
 */
public class PasswordGenerator {

	private ArrayList<String> words = new ArrayList<String>();
	
	/**
	 * Initialize the password generator with a word source.
	 * The word source is a file containing a list of newline separated
	 * English words of length between 3 and 7.
	 * located in "war/server/british-english-filtered.txt"
	 * @param path
	 */
	public PasswordGenerator(String path) {
		try {
			BufferedReader in = new BufferedReader(new FileReader(path));
			String zeile = null;
			while ((zeile = in.readLine()) != null) {
				words.add(zeile);

			}
		} catch (IOException e) {
			//System.out.println("[ERROR] PasswordGenerator failed to initialize");
			//System.out.println("Working directory : " + new File(".").getAbsolutePath());
			//debug: e.printStackTrace();
		}
	}
	
	/**
	 * This constructor is used to feed the PasswordGenerator with
	 * a explicitly specified set of words to construct passwords from.
	 * The minimum length of each word is 3.
	 * 
	 * @param words Words to construct passwords from
	 */
	public PasswordGenerator(String[] words) {
		ArrayList<String> wordlist = new ArrayList<String>();
		for (String word : words) {
			if (word.length() >= 3)
				wordlist.add(word);
		}
		this.words = wordlist;
	}

	/**
	 * Generate a random password, consists out of 3 English words.
	 * 
	 * @return password which consists out of 3 english words.
	 */
	public String newPassword() {
		StringBuilder result = new StringBuilder();

		try {

			for (int i = 0; i <= 2; i++) {
				result.append(
						words.get((int)Math.floor(Math.random() * (double)words.size()))
						);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result.toString();
	}
}
